package cn.edu.zxj.order.service.controller;

import cn.edu.zxj.order.service.model.OrderInfo;
import cn.edu.zxj.order.service.model.ProductInfo;
import cn.edu.zxj.order.service.service.OrderService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.eureka.EurekaServiceInstance;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description：
 *
 * @author: zxj
 * @date: 2024-09-28
 * @time: 12:29:25
 */

@RequestMapping("/order")
@RestController
@Slf4j
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private RestTemplate restTemplate;
    @Resource
    private DiscoveryClient discoveryClient;

    @RequestMapping("/test")
    public String test() {
        return "order service test";
    }

    @RequestMapping("/{orderId}")
    public OrderInfo getOrderInfoById(@PathVariable("orderId") Integer id) {
        OrderInfo orderInfo = orderService.getOrderInfoById(id);
        // String url = "http://127.0.0.1:8081/product/" + orderInfo.getProductId();
        //根据应⽤名称获取服务列表
        List<ServiceInstance> instances = discoveryClient.getInstances("product-service");
        //服务可能有多个, 获取第⼀个
        EurekaServiceInstance instance = (EurekaServiceInstance) instances.get(0);

        // 日志
        log.info(instance.getInstanceId());
        log.info(instance.getUri().toString());

        // 拼接url
        String url = instance.getUri() + "/product/" + orderInfo.getProductId();

        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
        orderInfo.setProductInfo(productInfo);
        return orderInfo;
    }
}
